﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * This file is part of dnAnalytics.  dnAnalytics is licensed under the 
 * Microsoft Public License. See License.txt for a complete copy of the
 * license.
 */

using System;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Bernoulli distribution is a distribution over bits. The parameter
    /// p specifies the probability that a 1 is generated.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Bernoulli : IDiscreteDistribution
    {
        /// <summary>
        /// The probability of generating a one.
        /// </summary>
        private readonly double mProbOne;

        /// <summary>
        /// Construct a new Bernoulli distribution.
        /// </summary>
        /// <param name="p">The probability of generating 1.</param>
        /// <exception cref="ArgumentOutOfRangeException">If the Bernoulli parameter is not in [0,1].</exception>
        public Bernoulli(double p)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(p);
            }

            mProbOne = p;
            RandomNumberGenerator = new System.Random();
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        public double Mean
        {
            get { return mProbOne; }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        public double StdDev
        {
            get { return System.Math.Sqrt(mProbOne*(1.0 - mProbOne)); }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        public double Variance
        {
            get { return mProbOne*(1.0 - mProbOne); }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        public double Entropy
        {
            get { return -mProbOne*System.Math.Log(mProbOne) - (1.0 - mProbOne)*System.Math.Log(1.0 - mProbOne); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IDiscreteDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        public int Mode
        {
            get { return mProbOne > 0.5 ? 1 : 0; }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        public int Median
        {
            get { throw new Exception("The median of the Bernoulli distribution is undefined."); }
        }

        /// <summary>
        /// Computes the probability of a specific value.
        /// </summary>
        public double Probability(int val)
        {
            if (val == 0)
            {
                return 1.0 - mProbOne;
            }
            if (val == 1)
            {
                return mProbOne;
            }
            return 0.0;
        }

        /// <summary>
        /// Samples a Bernoulli distributed random variable.
        /// </summary>
        public int Sample()
        {
            return DoSample(RandomNumberGenerator, mProbOne);
        }

        /// <summary>
        /// Samples an array of Bernoulli distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public int[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mProbOne);
        }

        #endregion

        private static void CheckParameters(double p)
        {
            if (p < 0.0 || p > 1.0)
            {
                throw new ArgumentOutOfRangeException("p", Resources.ZeroOneRange);
            }
        }

        /// <summary>
        /// Computes the cumulative distribution function.
        /// </summary>
        public double CumulativeDistribution(int val)
        {
            if (val < 0)
            {
                return 0.0;
            }
            if (val == 0)
            {
                return 1.0 - mProbOne;
            }

            return 1.0;
        }

        /// <summary>
        /// Samples a Bernoulli distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="p">The probability of generating a 1.</param>
        public static int Sample(System.Random rnd, double p)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(p);
            }

            return DoSample(rnd, p);
        }

        /// <summary>
        /// Samples an array of Bernoulli distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="p">The probability of generating a 1.</param>
        public static int[] Sample(System.Random rnd, int n, double p)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(p);
            }

            return DoSample(rnd, n, p);
        }

        private static int DoSample(System.Random rnd, double p)
        {
            if (rnd.NextDouble() < p)
            {
                return 1;
            }

            return 0;
        }

        private static int[] DoSample(System.Random rnd, int n, double p)
        {
            int[] ret = new int[n];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = DoSample(rnd, p);
            }
            return ret;
        }
    }
}